package com.powernode.filter.password;

import com.powernode.handler.LoginFailHandler;
import com.powernode.handler.LoginSuccessHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: powernode
 */
public class AccountLoginFilter extends AbstractAuthenticationProcessingFilter {


    private final LoginFailHandler failureHandler;

    private final LoginSuccessHandler successHandler;

    public AccountLoginFilter(AuthenticationManager authenticationManager,
                              LoginFailHandler failureHandler,
                              LoginSuccessHandler successHandler) {
        // 匹配登陆路径
        super("/account/login", authenticationManager);
        this.failureHandler = failureHandler;
        this.successHandler = successHandler;
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        System.out.println("AccountLoginFilter登陆");
        // 这里主要做请求的参数校验
        AccountToken accountToken = new AccountToken();
        accountToken.setUsername("admin");
        accountToken.setPwd("123");
        return this.getAuthenticationManager().authenticate(accountToken);
    }


    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        successHandler.onAuthenticationSuccess(request, response, chain, authResult);
    }


    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        failureHandler.onAuthenticationFailure(request, response, failed);
    }
}
